<?php
/**
 * Created by PhpStorm.
 * User: zhangfulai
 * Date: 2018/10/30
 * Time: 上午10:46
 */
namespace app\reserve\controller;
use app\reserve\model\Washcash as WashcashModel;
use think\Cache;
use think\cache\driver\Redis;
use app\reserve\model\Orderwash ;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use app\api\model\Cash as CashModel;

class Washcash extends Controller{
    public function selectWashcash(Request $request){
        $Washcash = new WashcashModel;
        $postData = $request->post();
        $check = $this->validate($postData,"WashcashValidate.selectWashcash");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        $pageNum = $postData["pagenum"];
        $listNum = $postData["listNum"];
        if(empty($listNum)){
            $listNum = 10;
        }
        if(!empty($postData["washid"])){
            $w["c.washid"] = $postData["washid"];
        }
        $w["c.status"] = array('NEQ',9);
        if(!empty($postData["name"])){
            $w['c.name'] = array('LIKE','%'.trim($postData["name"]).'%');
        }
        if(!empty($postData["status"])){
            $w["c.status"] = $postData["status"];
        }
        if(!empty($postData["start_time"]) && !empty($postData["end_time"])){
            $start_time = $postData["start_time"] ." 00:00:00";
            $end_time = $postData["end_time"] . " 23:59:59";
            $w['c.ctime'] = array(array('EGT',strtotime($start_time)),array('ELT',strtotime($end_time)),'and');
        }
        $result = $Washcash->selectWashcash($pageNum,$listNum,$w);
        $list = $result["list"];
        $attestation = $result["attestation"];
        $count = count($list);
        $returnarray["list"] = $result["list"];
        $count3 = count($attestation);
        for($i = 0; $i<$count;$i++){
            for($j = 0;$j<$count3;$j++){
                if($list[$i]["washid"] == $attestation[$j]["washid"]){
                    if(!empty($attestation[$j]["att_name"]) && !empty($attestation[$j]["pic_path"])){
                        $arrayname = explode(',',$attestation[$j]["att_name"]);
                        $arraypic =  explode(',',$attestation[$j]["pic_path"]);
                        $count2 = count($arrayname);
                        $array = array();
                        for($x = 0; $x<$count2;$x++){
                            array_push($array,["name"=>$arrayname[$x],"pic"=>$arraypic[$x]]);
                        }
                    }else{
                        $array = [];
                    }
                    $returnarray["list"][$i]["attestation"] = $array;
                    array_splice($attestation,$j,1);
                    $j--;
                    $count3 = count($attestation);
                }
            }

        }
        $returnarray["total"] =  $result["total"];
        if (!empty($result["list"])){
            return apiResponse(200,"查询成功",$result);
        }else{
            return apiResponse(200,"数据为空",$result);
        }
    }
    /*
    * Notes: 添加洗车商户
    * Create Date: 2018/10/27
    * Create Time: 17:28
    * Create by :张福来
    * Param :
    *  account：商户登录账号
    *  name：商户名称
    *  contactnum：联系电话
    *  legal_person：法人姓名
    *  id_number：法人身份证号
    *  password：登录密码
    *  ctime：创建时间
    *  wallet：账户余额
    *  score：评分
    *  添加成功返回 code:200
    *  添加失败返回 code:201
    */
    public function addWashcash(Request $request){
        $Washcash = new WashcashModel;
        $postData = $request->post();
        $check = $this->validate($postData,"WashcashValidate.addWashcash");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        if(empty($postData["account"])){
            return apiResponse(201,"洗车商户登录账号不能为空","");
        }else{
            $sql = Db::name('washcash')
                ->where(array("account" =>$postData["account"],'status'=>array('neq','9')))
                ->column("account");
            if(!empty($sql)){
                return apiResponse(201,"洗车商户已注册","");
            }
        }
        $password = substr($postData["account"],-6);
        $postData["password"] = md5($password);
        $postData["ctime"]=time();
        $postData["utime"]=time();
        $reslt = $Washcash ->addWashcash($postData);
        if($reslt){
            return apiResponse(200,"洗车商户注册成功",["washid"=>$reslt]);
        }else{
            return apiResponse(201,"洗车商户注册失败","");
        }
    }
    /*
    * Notes: 修改洗车商户
    * Create Date: 2018/10/27
    * Create Time: 17:28
    * Create by :张福来
    * Param :
    *  a_id：商户id
    *  account：商户登录账号
    *  name：商户名称
    *  contactnum：联系电话
    *  legal_person：法人姓名
    *  id_number：法人身份证号
    *  password：登录密码
    *  utime：修改时间
    *  添加成功返回 code:200
    *  添加失败返回 code:201
    */
    public function editWashcash(Request $request){
        $Washcash = new WashcashModel;
        $postData = $request->post();
        $check = $this->validate($postData,"WashcashValidate.editWashcash");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        if(!empty($postData['password'])){
            $postData["password"] = md5($postData["password"]);
        }
        $postData["utime"]=time();
        $reslt = $Washcash ->editWashcash($postData);
        if($reslt){
            return apiResponse(200,"洗车商户修改成功","");
        }else{
            return apiResponse(201,"洗车商户修改失败","");
        }
    }
    /*
    * Notes:删除洗车商户
    * Create Date: 2018/10/28
    * Create Time: 14:01
    * Create by :张福来
    * $a_id : 商户id
    */
    public function deletWashCash(Request $request){
        $Washcash = new WashcashModel;
        $postData = $request->post();
        $washid = $postData["washid"];
        $reslt = $Washcash->deleteWashcash($washid);
        if($reslt){
            return apiResponse(200,"洗车商户删除成功","");
        }else{
            return apiResponse(201,"洗车商户删除失败","");
        }
    }

    /**
     * Notes: 商户设置和修改洗车门店的提现比例
     * Create Date: 2018/10/2
     * Create Time: 15:34
     * Create by :lijie
     */
    public function setAllowRadio()
    {
        $id   = input('post.id');
        $a_id = input('post.a_id');
        if(empty($id) && empty($a_id)){
            return apiResponse(201,'参数错误','');
        }
        //
        $Washcash = new WashcashModel;
        $data['allowradio'] = input('post.allowradio');
        $where['a_id']      = $a_id;
        $where['washid']    = $id;
        $res = $Washcash->save($data,$where);
        if($res){
            return apiResponse(200,"提现比例设置成功",$res);
        }else{
            return apiResponse(201,"提现比例设置失败",$res);
        }
    }
    /*
    * Notes: 确认洗车订单
    * Create Date: 2018/10/7
    * Create Time: 下午3:59
    * Create by :张福来
    * param :
    */
    public function makesureOrder(Request $request){
        $orderwash = new Orderwash();
        $redis = new Redis(Config::get("redis"));
        $postData = $request->post();
        $check = $this->validate($postData,"WashcashValidate.makesureOrder");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        $key = "WashOrder".$postData["washid"].$postData["code"];
        if($redis->has($key)){
            $ordernumber = $redis->get($key);
            $result = $orderwash->makesureOrder($ordernumber,$postData);
            if($result){
                return apiResponse(200,"成功",$result);
            }else{
                return apiResponse(201,"失败",$result);
            }
        }else{
            return apiResponse(201,"付款码失效","");
        }
    }
    /**
     * Notes: 洗车商户登錄
     * Create Date: 2018/10/2
     * Create Time: 15:34
     * Create by :张福来
     */
    public function washlogin(Request $request){
        $Washcash = new WashcashModel();
        // 获取数据并验证
        $param = $request->post();
        $resVali = $this->validate($param,"WashcashValidate.washlogin");
        if($resVali !== true){
            return apiResponse(201,$resVali,'');
        }
        $account    = $param['account'];
        $password   = $param['password'];
        // 用户是否存在
        $w['account']   = $account;
        $w['status']    = 0;
        $cashInfo = $Washcash->findCash($w);

        if($cashInfo){
            // 密码正确否
            if($cashInfo['password'] == md5($password)){
                $save['last_login_time']    = time();
                $save['last_login_ip']      = $_SERVER['REMOTE_ADDR'];
                $save['washid']               = $cashInfo['washid'];
                $res = $Washcash->editWashCash($save);
                if($res){
                    return apiResponse(200,'登录成功',$cashInfo['washid']);
                }else {
                    return apiResponse(201,'登录失败','');
                }
            }else {
                return apiResponse(201,'密码不正确','');
            }
        }else{
            return apiResponse(201,'该账号不存在','');
        }
    }

    /**
     * Notes:  修改密码
     * Create Date: 2018/10/7
     * Create by :lijie
     */
    public function editPass(Request $request)
    {
        $Washcash = new WashcashModel();
        $param = $request->post();
        $resVali = $this->validate($param,"WashcashValidate.editPass");
        if($resVali !== true){
            return apiResponse(201,$resVali,'');
        }
        // 是否发送短信
        if (!empty($param['phone']) && empty($param['code'])){
            // 发短信
            $verify = mt_rand(1000,9999);
            $code['code'] = $verify;
            $res = sendSMS($param['phone'],"SMS_141617076",$code);
            if($res->Code == "OK"){
                Cache::set("phonechangepassword".$param['phone'],$verify,120);
                return apiResponse(200,'短信发送成功',$res->Code);
            }else {
                return apiResponse(201,"短信发送失败",$res->Code);
            }
        }
        // 手机号空 验证码不空
        if (empty($param['phone']) && !empty($param['code'])){
            return apiResponse(201,'请输入手机号','');
        }
        // 全空
        if (empty($param['phone']) && empty($param['code'])){
            return apiResponse(201,'手机号不能为空','');
        }
        // 验证码判断
        $code = Cache::get("phonechangepassword".$param['phone']);
        if($code != $param['code']){
            return apiResponse(201,'验证码错误','');
        }
        $param['password'] = md5($param['password']);
        $res = $Washcash->editWashcash($param);
        if($res){
            // 清空缓存
            Cache::rm("phonechangepassword".$param['phone']);
            return apiResponse(200,'修改成功',$res);
        }else {
            return apiResponse(201,"修改失败，输入的密码与原密码不能相同",$res);
        }
    }

    /**
     * Notes:  忘记密码
     * Create Date: 2018/10/17
     * Create by :lijie
     */
    public function forgetPass(Request $request)
    {
        $param = $request->post();
        $Washcash = new WashcashModel();
        // 是否发送短信
        if (!empty($param['phone']) && empty($param['code']) && empty($param['password'])){
            // 判断账号是否存在
            $account = $Washcash->where('account',$param['phone'])->field("washid")->find();
            if (empty($account)){
                return apiResponse(201,'账号不存在','');
            }
            // 发短信，返回账户id
            $verify = mt_rand(1000,9999);
            $code['code'] = $verify;
            $res = sendSMS($param['phone'],"SMS_141617076",$code);
            if($res->Code == "OK"){
                // 验证码设置到缓存中，有效期2分钟
                Cache::set("phoneforgetpassword".$param['phone'],$verify,120);
                return apiResponse(200,'短信发送成功',$account['washid']);
            }else {
                return apiResponse(201,"短信发送失败",$res->Code);
            }
        }
        // 判断验证码是否正确
        if (!empty($param['phone']) && !empty($param['code'])){
            if ($param['code'] == Cache::get('phoneforgetpassword'.$param['phone'])){
                return apiResponse(200,'验证码正确',1);
            }else {
                return apiResponse(201,'验证码错误',2);
            }
        }
        // 修改密码
        if (!empty($param['phone']) && !empty($param['password']) && empty($param['code'])){
            $where['account'] = $param['phone'];
            $data['password'] = md5($param['password']);
            $res = $Washcash->editWashByMobile($data,$where);
            if ($res){
                // 清空缓存
                Cache::rm('phoneforgetpassword'.$param['phone']);
                return apiResponse(200,'修改成功',$res);
            }else {
                return apiResponse(201,'修改失败，输入的密码与原密码不能相同',$res);
            }
        }
    }

    /**
     * Notes:  洗车商户更绑手机号
     * Create Date: 2018/10/9
     * Create by :lijie
     */
    public function bindPhone(Request $request)
    {
        $Washcash = new WashcashModel();
        $param = $request->post();
        // 验证码空
        if (!empty($param['phone']) && empty($param['code'])){
            // 发短信
            $verify = mt_rand(1000,9999);
            $code['code'] = $verify;
            $res = sendSMS($param['phone'],"SMS_139230931",$code);
            if($res->Code == "OK"){
                Cache::set("phonechangephone".$param['phone'],$verify,120);
                return apiResponse(200,'短信发送成功',$res->Code);
            }else {
                return apiResponse(201,"短信发送失败",$res->Code);
            }
        }
        // 手机号空
        if (empty($param['phone']) && !empty($param['code'])){
            return apiResponse(201,'手机号不能为空','');
        }
        // 全空
        if (empty($param['phone']) && empty($param['code'])){
            return apiResponse(201,'参数不全','');
        }
        // 验证码判断
        if ($param['code'] != Cache::get("phonechangephone".$param['phone'])){
            return apiResponse(201,'短信验证码不正确或已经过期','');
        }
        $param['account'] = $param['phone'];
        $res = $Washcash->editWashcash($param);
        if($res){
            // 清除缓存
            Cache::rm("phonechangephone".$param['phone']);
            return apiResponse(200,'绑定成功',$res);
        }else {
            return apiResponse(201,"绑定失败",$res);
        }
    }

    /**
     * Notes:  附近的洗车商户
     * Create Date: 2018/10/10
     * Create by :lijie
     *
     * param : pagenum
     * param : pageList
     * param : lat
     * param : lnt
     */
    public function nearWash(Request $request)
    {
        $Washcash = new WashcashModel();
        $param  = $request->post();
        if (empty($param['lat']) && empty($param['lnt'])){
            return apiResponse(201,'经纬度参数错误','');
        }
        $where['w.status'] = array("NEQ",9);
        $res['list']  = $Washcash->near($where,$param['pagenum'],$param['listNum'],$param['lat'],$param['lon']);
        $res['total'] = $Washcash->alias("w")->where($where)->count();
        if($res){
            return apiResponse(200,'获取成功',$res);
        }else {
            return apiResponse(201,"获取失败",$res);
        }
    }

    /**
     * Notes:  洗车商户添加认证
     * Create Date: 2018/10/13
     * Create by :lijie
     * param：washid
     * param：attestation_id
     */
    public function addAttestation(Request $request)
    {
        $Washcash = new WashcashModel();
        // 验证
        $param = $request->post();
        $resVali = $this->validate($param,"WashcashValidate.addAttestation");
        if($resVali !== true){
            return apiResponse(201,$resVali,'');
        }
        //
        $res = $Washcash->editWashcash($param);
        if($res){
            return apiResponse(200,'添加认证成功',$res);
        }else {
            return apiResponse(201,"添加认证失败",$res);
        }
    }

    /**
     * Notes:  洗车商户重置密码
     * Create Date: 2018/10/21
     * Create by :lijie
     * param:type   1 商户  2：洗车商户
     * param:id     商户id或洗车门店id
     */
    public function resetPass()
    {
        $id = input('post.id');
        $type = input('post.type');
        if (empty($id) || empty($type)){
            return apiResponse(201,'id或type不能为空','');
        }
        // 根据type类型判断重置密码是商户还似乎洗车门店
        if ($type == 1){
            $model = new CashModel();
            $phone = $model->where('a_id',$id)->value("account");
            $param['password'] = md5('orange2018');
            $param['utime']    = time();
            $where['a_id']     = $id;
            $res = $model->editCashAttest($param,$where);
        }else {
            $model = new WashcashModel();
            $phone = $model->where('washid',$id)->value("account");
            $param['password']  = md5('orange2018');
            $param['utime']     = time();
            $where['washid']    = $id;
            $res = $model->editWashByMobile($param,$where);
        }
        if ($res){
            return apiResponse(200,'密码已重置',$res);
        }else {
            return apiResponse(201,'重置失败',$res);
        }

    }

    /**
     * Notes:  上传图片
     * Create Date: 2018/10/23
     * Create by :lijie
     */
    public function uploadPic()
    {
        $upload_res=$_FILES['pic'];
        $tempfile = file_get_contents($upload_res['tmp_name']);     // 把整个文件读入一个字符串中。

        $tagArr = explode(".", $upload_res['name']);
        $tag_sel = array_shift($tagArr);
        $tag_end = end($tagArr);

        $path = 'upload/'.uniqid().".".$tag_sel.".".$tag_end;
        $res = file_put_contents($path, $tempfile);                 // 把一个字符串写入文件中
        if( !empty($res)){
            return apiResponse(200,"上传成功！","/$path");
        }else{
            return apiResponse(201,"上传失败！",'');
        }
    }

}